package com.xtsoft.platform.base.database.controller;

import com.fasterxml.jackson.databind.JsonMappingException;
import com.xtsoft.core.controller.GenericController;
import com.xtsoft.core.repository.QueryFilter;
import com.xtsoft.core.repository.QueryResult;
import com.xtsoft.core.utils.ResultMsg;
import com.xtsoft.core.utils.StringUtils;

import com.xtsoft.platform.base.database.domain.DbSql;
import com.xtsoft.platform.base.database.service.DbConnectService;
import com.xtsoft.platform.base.database.service.DbSqlService;
import com.xtsoft.platform.base.system.domain.SysUser;
import com.xtsoft.platform.globe.utils.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.JsonParseException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URISyntaxException;
import java.text.ParseException;

 /**
 * 
 * @ClassName:  DbSql   
 * <p> SQL脚本处理类 </p>
 * @author: Codegen-代码生成器
 * @date:   2019年12月3日 上午10:59:46
 */
 @Tag(name = "SQL脚本--处理接口")   
@RestController
public class DbSqlController extends GenericController{
	
	private final Logger log = LoggerFactory.getLogger(DbSqlController.class);
	
	@Autowired	
	private DbSqlService dbSqlService;
	@Autowired
	private DbConnectService dbConnectService;
	
	
    /**
     *  <p>新增一个SQL脚本</p>  
     * @param dbSql 要新增的SQL脚本
     * @return ResponseEntity<ResultMsg>, ResultMsg的Data中包含 SQL脚本
     * @throws URISyntaxException 如果URI语法不正确，则抛URI语法异常                     
	 * @author Codegen-代码生成器
	 * @date 2020-08-18 10:19:07
    */
    @PostMapping("/dbSql/add")
    @Operation(summary="新增，根据前台传递的SQL脚本新增")
	@Parameter(name = "dbSql",description = "要新增的SQL脚本")
    public ResponseEntity<ResultMsg> add(@RequestBody DbSql dbSql) throws URISyntaxException {
		if(null == dbSql){
			return new ResponseEntity<ResultMsg>(new ResultMsg(false,"新增SQL脚本失败，传递的SQL脚本为空"),HttpStatus.OK); 
		}
		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("新增SQL脚本开始......", user.getLoginId(), user.getUsername(), getClientIp());
        if (!StringUtils.isEmpty(dbSql.getDbSqlId())) {
		    log.info("新增SQL脚本失败，新SQL脚本不能具有DbSqlId属性值", user.getLoginId(), user.getUsername(), getClientIp());
            return new ResponseEntity<ResultMsg>(new ResultMsg(false,"新增SQL脚本失败，新SQL脚本不能具有DbSqlId属性值"),HttpStatus.OK);
        }
        //新增DbConnect
        dbSql.setDbConnect(dbConnectService.get(dbSql.getDbConnect().getDbConnectId()));
        //保存 save 添加到数据库中
//        DbSql sql=new DbSql();
//        sql.setSql("123123");
//        DbConnect db=new DbConnect();
//        db.setDbConnectId("4028812173eb40230173ebd767e20000");
//        sql.setDbConnect(db);
//        sql.setSqlName("123123");
//        sql.setDescript("12323");
        DbSql result = dbSqlService.save(dbSql);
		log.info("新增SQL脚本成功", user.getLoginId(), user.getUsername(), getClientIp());
        return new ResponseEntity<ResultMsg>(new ResultMsg(true,"新增成功",result),HttpStatus.OK);
    }	

    /**
     * <p>更新一个SQL脚本</p>    
     * @param dbSql 要更新的SQL脚本
     * @return ResponseEntity<ResultMsg>, json格式
     * @throws URISyntaxException 如果URI语法不正确，则抛URI语法异常
	 * @author Codegen-代码生成器
	 * @date 2020-08-18 10:19:07
     */
    @PostMapping("/dbSql/update")
    @Operation(summary="更新，根据传递的 SQL脚本更新实体")
	@Parameter(name = "dbSql",description = "要更新的SQL脚本")
	
    public ResponseEntity<ResultMsg> update(@RequestBody DbSql dbSql) throws URISyntaxException {
		if(null == dbSql){
			return new ResponseEntity<ResultMsg>(new ResultMsg(false,"更新SQL脚本失败，传递的SQL脚本为空"),HttpStatus.OK); 
		}
		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("单条更新SQL脚本开始......", user.getLoginId(), user.getUsername(), getClientIp());
		//若 SQL脚本无主键值，说明调用错误
        if (StringUtils.isBlank(dbSql.getDbSqlId())) {
			log.info("单条更新SQL脚本失败，SQL脚本对象DbSqlId无属性值", user.getLoginId(), user.getUsername(), getClientIp());
			return new ResponseEntity<ResultMsg>(new ResultMsg(false,"更新失败，SQL脚本对象DbSqlId无属性值"),HttpStatus.OK);
        }
        dbSqlService.flush();
        //添加DdConnect
        dbSql.setDbConnect(dbConnectService.get(dbSql.getDbConnect().getDbConnectId()));
        //保存
        DbSql result = dbSqlService.save(dbSql);
		log.info("单条更新SQL脚本成功", user.getLoginId(), user.getUsername(), getClientIp());
        return new ResponseEntity<ResultMsg>(new ResultMsg(true,"更新成功",result),HttpStatus.OK);
    }  

    /**
	 *   <p>查询SQL脚本列表，若分页，则页码信息在Request的参数中，包括当前页，每页记录数</p>
     * @return ResponseEntity<QueryResult<DbSql>>，json格式
     * @throws URISyntaxException 如果出错，则产生页码信息的 HTTP headers
	 * @author Codegen-代码生成器
	 * @date 2020-08-18 10:19:07
     */
    @GetMapping("/dbSql/getAll")
    @Operation(summary="查询，根据传递的条件查询SQL脚本列表，条件参数在Request中")

    public ResponseEntity<ResultMsg> getAll()
        throws URISyntaxException, JsonParseException, JsonMappingException, IOException, ParseException {
		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("获取SQL脚本列表开始......", user.getLoginId(), user.getUsername(), getClientIp());
        QueryFilter<DbSql> filter=new QueryFilter<DbSql>(DbSql.class);
        filter.addFilterFromRequest(request);
        QueryResult<DbSql> result= dbSqlService.anyQuery(filter);
		if(null == result || null == result.getResultList() || result.getResultList().size() < 0){
			log.info("获取SQL脚本列表失败", user.getLoginId(), user.getUsername(), getClientIp());
			return new ResponseEntity<ResultMsg>(new ResultMsg(false,"获取SQL脚本列表失败"),HttpStatus.OK);
		}
		log.info("获取SQL脚本列表成功", user.getLoginId(), user.getUsername(), getClientIp());
        return new ResponseEntity<ResultMsg>(new ResultMsg(true,"获取列表成功",result.getResultList()),HttpStatus.OK);
    }

    /**
	 *   <p>根据SQL脚本唯一ID值获取SQL脚本</p>
     * @param id SQL脚本唯一ID值
     * @return  ResponseEntity<DbSql>
	 * @author Codegen-代码生成器
	 * @date 2020-08-18 10:19:07		
     */
    @GetMapping("/dbSql/get/{id}")
    @Operation(summary="获取单个SQL脚本，若根据SQL脚本唯一Id获取到了多个对象则发生异常")
	@Parameter(name = "id",description = "对象唯一Id")
	
    public ResponseEntity<ResultMsg> get(@PathVariable String id) {
		if(StringUtils.isBlank(id)){
			 return new ResponseEntity<ResultMsg>(new ResultMsg(false,"获取单个SQL脚本失败，未给定SQL脚本的唯一标识"),HttpStatus.OK);
		}
		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("获取SQL脚本开始......", user.getLoginId(), user.getUsername(), getClientIp());
        DbSql dbSql = dbSqlService.get(id);
		/*
		*  <p> ofNullable执行逻辑：如果对象为空，则执行orElse，否则执行.map...
		*		return Optional.ofNullable(sysRole).map(result -> new ResponseEntity<>(result, HttpStatus.OK))
		*		.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));		
		*/
		
		if( null == dbSql ){
			log.info("获取SQL脚本失败", user.getLoginId(), user.getUsername(), getClientIp());
			return new ResponseEntity<ResultMsg>(new ResultMsg(false,"获取单个SQL脚本失败，给定的SQL脚本可能被删除"),HttpStatus.OK);
		}
		log.info("获取SQL脚本成功", user.getLoginId(), user.getUsername(), getClientIp());
		return new ResponseEntity<ResultMsg>(new ResultMsg(true,"获取成功",dbSql),HttpStatus.OK);
    } 

    /**
     *     <p>根据SQL脚本唯一ID值删除单个SQL脚本</p>
     * @param  id SQL脚本唯一ID值
     * @return ResponseEntity,json格式
	 * @author Codegen-代码生成器
	 * @date 2020-08-18 10:19:07		 
     */
    @GetMapping("/dbSql/delete/{id}")
    @Operation(summary="删除单个SQL脚本")
	@Parameter(name = "id",description = "SQL脚本唯一Id")
    public ResponseEntity<ResultMsg> delete(@PathVariable String id) {
		if(StringUtils.isBlank(id)){
			 return new ResponseEntity<ResultMsg>(new ResultMsg(false,"删除单个SQL脚本失败，未给定SQL脚本的唯一标识"),HttpStatus.OK);
		}
		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("删除单条SQL脚本开始......", user.getLoginId(), user.getUsername(), getClientIp());
		dbSqlService.remove(id);
		log.info("删除单条SQL脚本成功", user.getLoginId(), user.getUsername(), getClientIp());
        return new ResponseEntity<ResultMsg>(new ResultMsg(true,"删除成功"),HttpStatus.OK);
    }
	
    /**
     *     <p>根据SQL脚本唯一ID值集合，批量删除SQL脚本</p>
     * @param  ids SQL脚本唯一ID值集合
     * @return ResponseEntity<ResultMsg>,返回结果中有删除的记录数，json格式
	 * @author Codegen-代码生成器
	 * @date 2020-08-18 10:19:07		 
     */
    @PostMapping("/dbSql/deleteBatch")
    @Operation(summary="删除SQL脚本集合")
	@Parameter(name = "ids",description = "逗号分隔的SQL脚本Id集合")
    public ResponseEntity<ResultMsg> deleteBatch(@RequestParam String ids) {
		if(StringUtils.isBlank(ids)){
			 return new ResponseEntity<ResultMsg>(new ResultMsg(false,"批量删除SQL脚本失败，未给定SQL脚本的唯一标识集合"),HttpStatus.OK);
		}
		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("批量删除SQL脚本开始......", user.getLoginId(), user.getUsername(), getClientIp());
        long rows = dbSqlService.deleteBatch(ids);
		log.info("批量删除SQL脚本成功", user.getLoginId(), user.getUsername(), getClientIp());
        return new ResponseEntity<ResultMsg>(new ResultMsg(true,"批量删除SQL脚本成功",rows),HttpStatus.OK);
    }
	
    /**
     *     <p>根据SQL脚本唯一ID值集合，批量更新SQL脚本</p>
     * @param  ids SQL脚本唯一ID值集合
	 * @param  properityName SQL脚本要更新的属性名，不带类名
	 * @param  properityValue SQL脚本要更新的属性值
     * @return ResponseEntity<ResultMessage>,返回结果中有更新的记录数，json格式
	 * @author Codegen-代码生成器
	 * @date 2020-08-18 10:19:07		 
     */
    @PostMapping("/dbSql/updateBatch")
    @Operation(summary="更新SQL脚本集合")
	@Parameters({
			@Parameter(name = "properityValue", description="属性值", required = false),
			@Parameter(name = "ids", description="逗号分隔的仪表盘Id集合", required = false)})
    public ResponseEntity<ResultMsg> updateBatch(@RequestParam String properityName,
		@RequestParam String properityValue,
		@RequestParam String ids) {
		if(StringUtils.isBlank(ids) || StringUtils.isBlank(properityValue) || StringUtils.isBlank(properityName)){
			 return new ResponseEntity<ResultMsg>(new ResultMsg(false,"批量更新SQL脚本失败，未给定SQL脚本的唯一标识集合或属性名或属性值"),HttpStatus.OK);
		}
		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("批量更新SQL脚本开始......", user.getLoginId(), user.getUsername(), getClientIp());
        long rows = dbSqlService.updateBatch(properityName,properityValue,ids);
		log.info("批量更新SQL脚本成功", user.getLoginId(), user.getUsername(), getClientIp());
        return new ResponseEntity<ResultMsg>(new ResultMsg(true,"批量更新SQL脚本成功",rows),HttpStatus.OK);
    }	
}
